<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`选择-${title}`"
			width="1000px"
			append-to-body
			@on-visible-change="onVisibleChange"
			@on-cancel="onVisibleChange(false)"
			@on-confirm="onConfirmBtn"
		>
			<header ref="box1" class="margin-bottom-4 flex-between-center">
				<el-button size="small" icon="el-icon-plus" @click="onAddBtn">新增</el-button>
				<div>
					<jk-search-input :value="formData[`${apiMustQueryPrefix}Name`]" disabled class="search-bar-item-size3 item-gap" placeholder="品种编号或名称" @on-enter="onSearchBtn"></jk-search-input>
					<jk-search-input v-model="searchParams.batchCode" class="search-bar-item-size3 item-gap" placeholder="批号" @on-enter="onSearchBtn"></jk-search-input>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</header>

			<jk-table
				ref="jkTable"
				:row-style="rowClassName"
				:loading="tableLoading"
				class="width-100-percent"
				:data="tableData"
				border
				row-id="id"
				highlight-hover-row
				:height="dialogTableHeight - 30"
				:radio-config="{trigger: 'row1', checkMethod: checkRadioMethod}"
				@radio-change="onRadioChange"
				@cell-dblclick="onCellDblclick"
			>
				<vxe-table-column type="radio" width="60" align="center" title="单选" fixed="left"></vxe-table-column>
				<vxe-table-column field="batchCode" title="批号" sortable :min-width="120" />
				<vxe-table-column field="batchDate" title="批号日期" fixed :width="140"> </vxe-table-column>
				<vxe-table-column field="productName" title="品种" min-width="280" />
				<vxe-table-column field="productModels" title="规格" min-width="180" />
				<vxe-column title="状态" align="center" field="auditState" :width="100">
					<template slot-scope="scope">
						<jk-common-status :status="scope.row.auditState"></jk-common-status>
					</template>
				</vxe-column>
			</jk-table>
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					layout="total, prev, pager, next"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-dialog>
		<create-dialog
			:is-default-product="true"
			:form-data="{
				batchCode: isDemoYarn ? formData.orderQty >= demoYarnInfo.minValue && formData.orderQty <= demoYarnInfo.maxValue ? demoYarnInfo.batchCode : '' : '',
				productId: formData[`${apiMustQueryPrefix}Id`],
				productCode: formData[`${apiMustQueryPrefix}Code`],
				productName: formData[`${apiMustQueryPrefix}Name`],
				productModels: formData[`${apiMustQueryPrefix}Models`],
			}"
			:dialog-state="createDialogState"
			@on-visible-change="onVisibleChangeOfCreateDialog"
			@on-finish="onFinishOfCreateCustomerDialog"
		></create-dialog>
	</div>
</template>

<script>
    import calDialogHeight from '../../../../../mixins/cal-dialog-height';
    import { pageConfig, tipsBar } from '../../../../../utils/jk/jk-tool';
    import { spinProductBatchPage } from '../../../../../api/material/batchCode';
    import createDialog from '../../../../material/batchCode/save-dialog';

    export default {
        components: {
            createDialog
        },
        mixins: [calDialogHeight],
        props: {
            selectedList: {
                type: Array,
                default() {
                    return [];
                }
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            apiMustQueryPrefix: { // 接口必须的条件前缀，比如：必传productId时, 传product即可
                type: String,
                default: 'productId'
            },
            title: {
                type: String,
                default: '批号'
            },
            isDemoYarn: {
                type: Boolean,
                default: false
            },
            demoYarnInfo: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        data() {
            return {
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    auditState: 1,
                    batchCode: '',
                    productId: null,
                    workshopId: null
                },
                selectRow: null,
                searchBarProcessId: null,
                searchBarNameOrCode: '',
                pageNo: 1,
                pageSize: pageConfig.pageSize,
                totalCount: null,
                tableData: [],
                showDialog: false,
                tableLoading: false,
                createDialogState: false,
                selectData: []
            };
        },
        methods: {
            onCellDblclick(e) {
                if (!this.selectedList.some(x => x.batchId === e.row.id)) {
                    this.$emit('on-confirm', e.row);
                } else {
                    tipsBar(this, 'custom', 'warning', '该批号已存在，请勿重复选择!');
                }
            },
            rowClassName(e) {
                if (this.selectedList.find(x => x.batchId === e.row.id)) {
                    return {
                        backgroundColor: '#c5c8ce',
                        color: '#fff'
                    };
                }
            },
            onAddBtn() {
                this.createDialogState = true;
            },
            onVisibleChangeOfCreateDialog(e) {
                this.createDialogState = e;
            },
            onFinishOfCreateCustomerDialog(id) {
                this.getListRequest(id);
                this.createDialogState = false;
            },
            checkRadioMethod(e) {
                return !this.selectedList.find(x => x.batchId === e.row.id);
            },
            onRadioChange(selection) {
                this.selectData = selection.row;
            },
            checkboxMethod({ row }) {
                return row._disabled !== true;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn() {
                if (Object.keys(this.selectData).length) {
                    this.$emit('on-confirm', this.selectData);
                } else {
                    this.$tipsBar(this, 'unChoose');
                }
            },
            getListRequest(id) {
                this.tableLoading = true;
                this.selectData = [];
                return spinProductBatchPage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.searchParams, 'count', res.data.count);
                        this.tableData = res.data.res || [];
                        if (id) {
                            this.selectData = this.tableData.find(x => x.id === id);
                            this.$emit('on-confirm', this.selectData);
                        }
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            async getDependentData() {
                this.tableLoading = true;
                const cpData = this.formData ? JSON.parse(JSON.stringify(this.formData)) : {};
                this.$set(this.searchParams, 'productId', cpData[`${this.apiMustQueryPrefix}Id`]);
                await this.getListRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
